<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" :rules="formRules" :model="formModel" label-width="120px">

      <el-form-item label="标题" prop="title">
        <el-input class="w100" v-model.trim="formModel.title" autocomplete="off" placeholder="请输入标题"></el-input>

      </el-form-item>

      <el-form-item label="封面" prop="image">
        <el-upload class="upload-demo"
                   ref="uploadRef"
                   accept="image/*"
                   :before-upload="onBeforeUpload"
                   :http-request="uploadk4" :file-list="fileList"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">关闭</el-button>
        <el-button type="primary" @click="onSubmit()" :loading="submitLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 管理员编辑组件
 */
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { roleParams } from '@/apis/model/RoleModel';
import { getNewObj } from '@/utils/EsCommon';

// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);

// 表单数据
const formAttrs = {
  id:null,
  title: "",
  image: ""
};
// 请选择系统类型



// 表单组件的引用实例
const formRef = ref(null);
// 表单校验规则
const formRules = ref({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  image: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],

})



const formModel = ref(Object.assign({}, formAttrs));

const uploadRef = ref(null)

const submitLoading = ref(false)

// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '600px',
})
// 表单组件的引用实例
const fileList = ref([])

// ======================================================
//                      点击操作
// ======================================================
const onBeforeUpload = (file)=>{
  fileList.value = [file]
  return true
}

// 点击取消按钮
const onCancel = () => {
  dialogInfo.value.visible = false;
}
// ======================================================
//                      处理事件
// ======================================================

// 加载数据
const show = async (id, title, item = null, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  fileList.value = []
  formModel.value.image = null
  formModel.value.title = item.title
  formModel.value.id = id
}
const uploadk4 = (file) => {
  // const formData = new FormData();
  // formData.append("file", file.file);
  // formData.append("system", formModel.value.radioK4);
  // formData.append("ftype", "k4");
  // formData.append("rid", 0);
  // const xhr = new XMLHttpRequest();
  // xhr.open("post", "/api/file/upload", true);
  // xhr.setRequestHeader("Authorization", localStorage.Authorization);
  // xhr.onload = (res) => {
  //   var json = JSON.parse(xhr.responseText);
  //   console.log('json==', json)
  //   if (json.code == 200) {
  //     ElMessage.success("上传成功");
  //     dialogInfo.value.visible = false;
  //     emit('success');
  //   } else {
  //     ElMessage.error(json.msg)
  //     fileList.value = []
  //
  //   }
  //
  //   // //console.log(json)
  // };
  //
  // xhr.onerror = () => {
  //   //console.log('上传失败');
  // };
  // xhr.ontimeout = function timeout() {
  //   //console.log('上传超时，请刷新重试');
  // };
  // xhr.send(formData);

  let reader = new FileReader();
  reader.readAsDataURL(file.file);
  reader.onload = () => {
    formModel.value.image = reader.result
  };
  reader.onerror = function () {
    ElMessage.error('图片上传失败')
  };
}

// 点击提交按钮
const onSubmit = async () => {
  console.log('submit!', formModel.value);
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    submitLoading.value = true
    EsAjax.post(ApiUrls.liveTaskChangeTitleImg,formModel.value ).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    }).finally(()=>(submitLoading.value = false))

  })
}




defineExpose({
  show
})
</script>

<style scoped>
</style>
